// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import ResultDialog from "./ResultDialog";
import Score from "./Score";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    // LIFE-CYCLE CALLBACKS:
    static inst: Game = null;

    // 得分
    score: Score = null;

    // 子弹Prefab
    @property(cc.Prefab)
    bulletPrefab: cc.Prefab = null;

    // 子弹对象池
    bulletPool: cc.NodePool = new cc.NodePool();

    // 子弹Prefab
    @property(cc.Prefab)
    shrapnelPrefab: cc.Prefab = null;

    @property({displayName:"背景音乐", type: cc.AudioClip})
    bgmAudio: cc.AudioClip = null;

    bgmAudioID: number = 0;

    // 散弹对象池
    shrapnelPool: cc.NodePool = new cc.NodePool();

    shrapnelNodes: cc.Node[] = [];

    // 目标Prefab
    @property(cc.Prefab)
    targetPrefab: cc.Prefab = null;
    
    // 目标对象池
    targetPool: cc.NodePool = new cc.NodePool();

    canvas: cc.Node = null;

    playing: boolean = false;

    // 结果提示框
    resultDlg: ResultDialog = null;

    stopOrGoOnBtn : cc.Label = null;

    onLoad () {

        Game.inst = this;

        this.canvas = cc.find('Canvas');
        this.resultDlg = cc.find('Canvas/结果提示框').getComponent(ResultDialog);

        this.stopOrGoOnBtn = cc.find('Canvas/暂停').getComponent(cc.Label);

        let manager = cc.director.getCollisionManager();
        manager.enabled = true;
        //manager.enabledDebugDraw = true;

    }

    startGame() {

        this.playing = true;

        // 创建目标
        this.schedule(this.onCreatingTarget, 3, cc.macro.REPEAT_FOREVER, 0.1);

        // 重置得分
        Score.i.clearScore();

        if (this.bgmAudio != null) {

            this.bgmAudioID = cc.audioEngine.playMusic(this.bgmAudio, true);
        }
    }
    
    gameOver() {

        cc.log('游戏结束...');

        this.playing = false;

        // 关闭定时器, 不再生成Target
        this.unschedule(this.onCreatingTarget);

        // 清理屏幕上的节点
        this.clearScreen();

        // 显示结果提示框
        this.resultDlg.show();

        if (this.bgmAudio != null) {

            cc.audioEngine.stop(this.bgmAudioID);
        }
    }

    clearScreen() {

        let nodes: cc.Node[] = this.canvas.children;

        //删除的是数组, 删除一个后, 节点索引会发生变化, 所以要倒着删除
        for (let i = nodes.length - 1; i >= 0; i--) {
            
            let node = nodes[i];

            if (node.name == '玩家子弹') {

                this.destroyBullet(node);
            }
            else if (node.name == '目标') {

                this.destroyTarget(node);
            }
            //else if (node.name == '散弹') {

                //this.destroyShrapnel(node);
           // }
        }
    }

    createBullet() {

        let node = this.bulletPool.get();

        if(node == null) {

            node = cc.instantiate(this.bulletPrefab);
        }

        return node;
    }

    destroyBullet(node: cc.Node) {
        
        this.bulletPool.put(node);
    }

    // 散弹
    createShrapnel(): cc.Node[] {

        let node_left = this.shrapnelPool.get();
        let node_middle = this.shrapnelPool.get();
        let node_right = this.shrapnelPool.get();

        if(node_left == null) {

            node_left = cc.instantiate(this.shrapnelPrefab);
        }

        if(node_left == null) {

            node_middle = cc.instantiate(this.shrapnelPrefab);
        }

        if(node_right == null) {

            node_left = cc.instantiate(this.shrapnelPrefab);
        }

        node_left.angle = -30;
        node_left.angle = 30;

        this.shrapnelNodes[0] = node_left;
        this.shrapnelNodes[1] = node_middle;
        this.shrapnelNodes[2] = node_right;

        return this.shrapnelNodes;
    }

    destroyShrapnel(nodes: cc.Node[]) {

        let i = nodes.length

        for (let i = 0; i < nodes.length; i++) {

            this.bulletPool.put(nodes[i]);
        }
    }

    createTarget() {

        let node = this.targetPool.get();

        if (node == null) {

            node = cc.instantiate(this.targetPrefab);
        }

        return node;
    }

    destroyTarget(node: cc.Node) {
        
        this.targetPool.put(node);
    }

    // 定时创建目标
    onCreatingTarget() {

        // 每排最少创建1个方块, 最多创建4个
        // Math.random()生成0.0 ~ 1.0的浮点数
        // Math.floor()取整
        let index: number = Math.floor(Math.random() * 4);

        for(let i = 0; i < 4; i++) {

            let flag = Math.floor(Math.random() * 2);
            if(flag == 0 && i != index) continue; // flag为1，则该位置也添加一块

            let targetNode: cc.Node = this.createTarget();
            targetNode.parent = this.canvas;  // 挂在Canvas节点下

            let w = this.canvas.width;
            let h = this.canvas.height;

            let unit = w / 4;
            targetNode.x = unit * i - w/2 + w/8;
            targetNode.y = (h / 2 + targetNode.height / 2) - 250; // 减去最顶的计分栏的高度
        }
    }

    stopOrGoOn() {

        if (this.playing == true) {

            this.playing = false;

            this.stopOrGoOnBtn.string = "继续";

            // 关闭定时器, 不再生成Target
            this.unschedule(this.onCreatingTarget);

            // 清理屏幕上的节点
            this.clearScreen();

            if (this.bgmAudio != null) {

                cc.audioEngine.stop(this.bgmAudioID);
            }
        }
        else if (this.playing == false) {

            this.playing = true;

            this.stopOrGoOnBtn.string = "暂停";

            // 创建目标
            this.schedule(this.onCreatingTarget, 3, cc.macro.REPEAT_FOREVER, 0.1);

            if (this.bgmAudio != null) {

                this.bgmAudioID = cc.audioEngine.playMusic(this.bgmAudio, true);
            }
        }
        
    }

    backToMainScene() {

        cc.director.loadScene('MainScene');
    }
}
